package com.zhida.smartcontrol.launch.bottom;

import android.content.Context;
import android.view.Gravity;
import android.widget.Toast;

import com.dyhdyh.widget.loadingbar2.LoadingBar;
import com.zhida.smartcontrol.R;
import com.zhida.smartcontrol.mvp.BasePresenterImpl;
import com.zhida.smartcontrol.mvp.BaseView;
import com.zhida.smartcontrol.mvp.permisson.PermissionCheckerFragment;
import com.zhida.smartcontrol.utils.CustomDialogFactory;

import java.lang.reflect.ParameterizedType;


/**
 * author: tanjianpei
 * date: 2019/7/11 011 15:56
 * description: 底部导航栏内部页面继承
 */
public abstract class BottomItemFragment<V extends BaseView, T extends BasePresenterImpl<V>> extends PermissionCheckerFragment implements BaseView {

    private long mExitTime = 0;
    private static final int EXIT_TIME = 1000;

    protected T mPresenter;

    @Override
    protected void initPresenter() {
        mPresenter = getInstance(this, 1);
        mPresenter.attachView((V) this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LoadingBar.release();
        if (mPresenter != null)
            mPresenter.detachView();
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    @Override
    protected void noPermission() {
        showTipsDialog(this);
    }

    @Override
    public void showLoading(String msg) {
        LoadingBar.dialog(getProxyActivity())
                //通过工厂设置样式
                .setFactory(new CustomDialogFactory(msg))
                //通过View设置样式
                //.setFactoryFromView(view)
                //通过布局ID设置样式
//                .setFactoryFromResource(R.layout.layout_loading)
                //携带参数
                .extras(new Object[]{})
                .show();
    }

    @Override
    public void hideLoading() {
        LoadingBar.dialog(getProxyActivity()).cancel();
    }

    @Override
    public void showMsg(String msg) {
        toast(msg);
    }

    @Override
    public boolean onBackPressedSupport() {
        if ((System.currentTimeMillis() - mExitTime) > EXIT_TIME) {
            Toast.makeText(getContext(), "再按一次退出" + getString(R.string.app_name)
                    , Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            _mActivity.finish();
            if (mExitTime != 0) {
                mExitTime = 0;
            }
        }
        return true;
    }

    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[i])
                    .newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
